﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Core.IRepository;
using System.Linq.Expressions;
using Core.Queries;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using Core.Messages;
using Library.Extensions.Expressions;

namespace Repositories
{
    public class QueryHelper<T> : IQueryHelper<T>            
    {
        public DbContext Context { get; set; }
        public QueryHelper() { }

        public QueryResponse<T> FindBy(DbContext context, IQueryable<T> set, Query<T> query)
        {
            this.Context = context;
            return FindBy(set, query);
        }

        public QueryResponse<T> FindBy(IQueryable<T> set, Query<T> query)
        {
            QueryResponse<T> response = new QueryResponse<T>();
            response.List = set.Query<T>(query).ToList();

            if (query.Count)
            {
                if (Context != null)
                    Context.Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
                response.TotalItemCount = set.Where(query).Count();
                if (Context != null)
                    Context.Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ COMMITTED;");
            }
            
            response.PageNumber = query.PageNumber;
            response.PageSize = query.PageSize;            
            return response;
        }
    }
}
